package com.zx.springsecurity.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.zx.springsecurity.entity.Users;
import com.zx.springsecurity.mapper.UsersMapper;

/**
 * 自定义UserDetailsService实现类
 * @author 郑雪
 * @date 2021-11-25
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
	
	@Autowired
	UsersMapper userMapper;

	/**
	 * 通过用户名加载用户
	 */
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		//查询数据库，根据用户名查询，把查询出来的用户名密码和权限封装为User对象返回
		Users user = new Users();
		//where username=?
		user.setUsername(username);
		Users dbUser = userMapper.selectOne(user);
		//判断
		if(dbUser == null){
			throw new UsernameNotFoundException("用户名不存在！");
		}
		//权限集合
		//List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("admin");
		List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
		return new User(dbUser.getUsername(), new BCryptPasswordEncoder().encode(dbUser.getPassword()), authorities);
	}

}
